package com.education.basic.ao.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.education.basic.action.BasicAction.LoginMsg;
import com.education.basic.ao.LoginAo;
import com.education.basic.entity.Administrator;
import com.education.basic.service.AdministratorService;
import com.yunshangwoniu.core.ValidateCodeService.ValidateCodeService;

import com.yunshangwoniu.core.cache.CacheAble;
import com.yunshangwoniu.core.utils.CookieUtils;
import com.yunshangwoniu.core.utils.Logger;
import com.yunshangwoniu.core.utils.RequestUtils;
import com.yunshangwoniu.core.utils.StringUtils;

@Service("loginAo")
public class LoginAoImpl implements LoginAo
{
	@Resource
	private ValidateCodeService validateCodeService;
	@Resource
	private AdministratorService administratorService;
	@Resource
	private CacheAble<Object, Object> cacheAble;
	private String domain = "127.0.0.1";
	
	@Override
	public String login(String username, String password, String validateCode, LoginMsg loginMsg, HttpServletRequest request, HttpServletResponse response)
	{
		Logger.debug(this.getClass(), String.format("excute login username:%s", username));
		if(StringUtils.isNullOrEmpty(username))
		{
			String msg = "用户名不能为空";
			loginMsg.setLoginMsg(msg);
			return "error";
		}
		if(StringUtils.isNullOrEmpty(password))
		{
			String msg = "密码不能为空";
			loginMsg.setLoginMsg(msg);
			return "error";
		}
		if(StringUtils.isNullOrEmpty(validateCode))
		{
			String msg = "验证码不能为空";
			loginMsg.setLoginMsg(msg);
			return "error";
		}
		if(validateCode.equalsIgnoreCase(validateCodeService.validate(request, validateCode)))
		{
			Administrator ad = administratorService.login(username, password);
			if(ad!=null)
			{
				cacheAble.put(RequestUtils.getIp(request), ad);								//放入缓存（只是tomcat模拟缓存）
				CookieUtils.createCookie(request, response, "username", username, -1, domain);
				Logger.debug(this.getClass(), String.format("login success username:%s validateCode:%s", username,validateCode));
				return "success";
			}else 
			{
				String msg = "用户名或者密码错误";
				loginMsg.setLoginMsg(msg);
				return "error";
			}
		}else 
		{
			String msg = "验证码错误";
			loginMsg.setLoginMsg(msg);
			return "error";
		}
		
	}

	@Override
	public String loginOut(String username, HttpServletRequest request, HttpServletResponse response)
	{
        cacheAble.put(RequestUtils.getIp(request), null);
        return "success";
	}

}
